<template>
     <div>
     <!-- 
      注意标签栏的跳转：必须是使用一个div包裹（div外不要元素）所有的页面组件
      @不然会无法点击跳转
     -->
     <!-- 
     @@@点击跳转的页面需要一个div包裹：
         是因为在Vue.js中，组件的结构需要被包裹在一个根元素（通常是div）内。
         在这个例子中，<template>标签内的代码就是一个Vue组件的模板，它包含了一个用于显示标签页的<el-tabs>组件和一个用于显示关闭选项的下拉菜单。
         这些元素都需要被包裹在一个根元素（如div）内，以便Vue能够正确地解析和渲染它们。
     -->
          <!-- 用户列表首页 -->
          <div class="top">
               名称：
               <!-- 
          输入的值不显示:
           是由于Vue.js的数据绑定没有正确设置导致的
           v-model="searchInfo"
            -->
               <el-input style="width: 240px" v-model="searchInfo" placeholder="请输入查询名称" />
               <div class="btnDiv">
                    <el-button :icon="Search" type="primary" @click="searchRun">搜索</el-button>
                    <el-button :icon="RefreshLeft" @click="{ searchInfo = '', RefreshUser(); }">重置</el-button>
               </div>
          </div>
          <div class="content">
               <div class="tool">
                    <div class="left">
                         <el-button :icon="Plus" type="warning" @click="EditORAddUser('Add')">新增</el-button>
                    </div>

                    <div class="right">
                         <div class="Refresh" @click="RefreshUser();"><el-icon>
                                   <RefreshRight />
                              </el-icon></div>
                         <div class="Setting">
                              <el-icon>
                                   <Setting />
                              </el-icon>
                         </div>
                    </div>
               </div>
               <!-- 用户列表显示 -->
               <div class="List">
                    <el-table ref="multipleTableRef" :data="userVoList" style="width: 100%" @selection-change="">
                         <el-table-column property="id" label="账号" />
                         <el-table-column property="name" label="姓名" />
                         <el-table-column property="age" label="年龄" />
                         <el-table-column property="university" label="大学" />
                         <el-table-column property="majors" label="专业" />
                         <el-table-column property="hobbies" label="爱好" />
                         <el-table-column property="avatar" label="头像">
                              <template v-slot="scope">
                                   <img :src="scope.row.avatar" alt="Avatar"
                                        style=" border-radius: 10px; width: 100%; height: auto;">
                              </template>
                         </el-table-column>
                         <el-table-column property="qqNum" label="QQ" />
                         <el-table-column property="qqImg" label="QQ二维码">
                              <template v-slot="scope">
                                   <img :src="scope.row.qqImg" alt="QQ二维码"
                                        style="border-radius: 10px; width: 100%; height: auto;">
                              </template>
                         </el-table-column>
                         <el-table-column property="wxNum" label="微信" />
                         <el-table-column property="wxImg" label="微信二维码">
                              <template v-slot="scope">
                                   <img :src="scope.row.wxImg" alt="微信二维码"
                                        style="border-radius: 10px; width: 100%; height: auto; ">
                              </template>
                         </el-table-column>
                         <el-table-column property="nickName" label="昵称" />
                         <el-table-column label="操作">

                              <template #default="scope">
                                   <el-button type="warning" @click="EditORAddUser('Edit', scope.row.id)">编辑</el-button>
                                   <el-button type="danger" @click="delUser(scope.row.id)">删除</el-button>
                              </template>
                         </el-table-column>
                    </el-table>
               </div>
          </div>

          <el-dialog v-model="centerDialogVisible" :title="`${operation}-用户`" width="500" align-center
               :show-close="false">
               <el-form :model="form" label-width="auto" style="max-width: 600px">
                    <el-form-item label="姓名：">
                         <el-input v-model="form.name" />
                    </el-form-item>
                    <el-form-item label="年龄：">
                         <el-input v-model="form.age" />
                    </el-form-item>
                    <el-form-item label="大学：">
                         <el-input v-model="form.university" />
                    </el-form-item>
                    <el-form-item label="专业：">
                         <el-input v-model="form.majors" />
                    </el-form-item>
                    <el-form-item label="爱好：">
                         <el-input v-model="form.hobbies" />
                    </el-form-item>
                    <el-form-item label="头像">
                         <el-upload class="avatar-uploader" action="#" :http-request="uploadFile" :auto-upload="true"
                              :show-file-list="false" :on-success="handleAvatarSuccessAvatar">
                              <img v-if="form.avatar != null" :src="form.avatar" width="50" height="50"
                                   class="avatar" />
                              <el-icon v-else class="avatar-uploader-icon"
                                   style="background-color:  rgb(252, 248, 248);padding: 20px;border-radius: 5px;"
                                   width="50" height="50">
                                   <Plus />
                              </el-icon>
                         </el-upload>
                    </el-form-item>
                    <el-form-item label="QQ：">
                         <el-input v-model="form.qqNum" />
                    </el-form-item>
                    <el-form-item label="QQ二维码：">
                         <el-upload class="avatar-uploader" action="#" :http-request="uploadFile" :auto-upload="true"
                              :show-file-list="false" :on-success="handleAvatarSuccessQQImg" key="qqImg">
                              <img v-if="form.qqImg != null" :src="form.qqImg" width="50" height="50" class="avatar" />
                              <el-icon v-else class="avatar-uploader-icon"
                                   style="background-color:rgb(252, 248, 248);padding: 20px;border-radius: 5px;"
                                   width="50" height="50">
                                   <Plus />
                              </el-icon>
                         </el-upload>
                    </el-form-item>
                    <el-form-item label="微信：">
                         <el-input v-model="form.wxNum" />
                    </el-form-item>
                    <el-form-item label="微信二维码：">
                         <el-upload class="avatar-uploader" action="#" :http-request="uploadFile" :auto-upload="true"
                              :show-file-list="false" :on-success="handleAvatarSuccessWXImg" key="avatar">
                              <img v-if="form.wxImg != null" :src="form.wxImg" width="50" height="50" class="avatar" />
                              <el-icon v-else class="avatar-uploader-icon"
                                   style="background-color: rgb(252, 248, 248);padding: 20px;border-radius: 5px;"
                                   width="50" height="50">
                                   <Plus />
                              </el-icon>
                         </el-upload>
                    </el-form-item>
                    <el-form-item label="Q昵称：">
                         <el-input v-model="form.nickName" />
                    </el-form-item>
               </el-form>
               <template #footer>
                    <div class="dialog-footer">
                         <el-button type="primary" @click="submitFrom(operation)">
                              保存
                         </el-button>
                         <el-button @click="close">取消</el-button>
                    </div>
               </template>
          </el-dialog>
     </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, UploadProps, ElMessageBox } from 'element-plus'
import { Search, RefreshLeft, Plus } from '@element-plus/icons-vue'
import { userList, userListById, uploadBinaryImage, AddUser, EditUser, DeleteUser, userListLikeName } from '@/api';
//表单显示的用户数据
let userVoList = ref([])
let searchInfo = ref('')
// 控制Dialog显示状态
const centerDialogVisible = ref(false)
// 操作类型（添加或者修改）
const operation = ref('')
// 初始化表单对象
const form = reactive({
     id: null,
     name: '',
     age: null,
     university: '',
     majors: '',
     hobbies: '',
     avatar: null,
     qqNum: '',
     qqImg: null,
     wxNum: '',
     wxImg: null,
     nickName: ''
})

const RefreshUser = async () => {
     let { data } = await userList();
     userVoList.value = data.data
}

// 挂载页面的时候请求一次用户数据
onMounted(async () => {
     RefreshUser();
})
// 根据输入的名称搜索用户信息
const searchRun = async () => {
     if (searchInfo.value != '') {
          let reslut = await userListLikeName(searchInfo.value)
          userVoList.value = reslut.data.data
     }
     else {
          RefreshUser();
     }
}

// 添加或者修改用户
const EditORAddUser = async (type: string, id?: number) => {
     operation.value = type === "Add" ? '添加' : '编辑'
     if (type != 'Add') {
          let { data } = await userListById(id)
          Object.assign(form, data.data);
     }
     centerDialogVisible.value = true
}
//清除from表单数据
const clearForm = () => {
     Object.keys(form).forEach(key => {
          form[key] = null; // 或者设为 null 或其他适当的初始值  
     });
};
//关闭添加或者修改用户的dialog
const close = () => {
     clearForm();
     centerDialogVisible.value = false
}
// 文件上传接口
/**
 * 使用 :http-request="uploadFile"替代action:""方法
 * 会自动传入一个fileObj对象，里面包含了选择的文件对象
 * 		{headers: {…}, withCredentials: false, file: File, data: {…}, method: 'post', …}
 * */
let reslutData = ref()
let imgUrl = ref()
const uploadFile = async (fileObj) => {
     // 传给后端 MultipartFile 参数 需要的格式
     const formData = new FormData();
     /**
      * fileObj对象里面包含了选择的file对象
      * .append(
      * 		参数一：后端需要的参数名称保持一致,
      *  		参数二：文件对象
      * );
      * */
     formData.append('file', fileObj.file);
     try {
          let reslut = await uploadBinaryImage(formData)
          if (reslut.status === 200) {
               reslutData.value = reslut.data.data
               return ElMessage.success("文件上传成功....")
          }
          ElMessage.error('文件上传失败')
     } catch (error) {
          ElMessage.error('文件上传失败', error)
     }
};

//图片上传成功显示
const handleAvatarSuccessAvatar: UploadProps['onSuccess'] = (
     response,
     uploadFile,
) => {
     imgUrl.value = reslutData.value
     form.avatar = imgUrl.value.url
}
const handleAvatarSuccessQQImg: UploadProps['onSuccess'] = (
     response,
     uploadFile,
) => {
     imgUrl.value = reslutData.value
     form.qqImg = imgUrl.value.url
}
const handleAvatarSuccessWXImg: UploadProps['onSuccess'] = (
     response,
     uploadFile,
) => {
     imgUrl.value = reslutData.value
     form.wxImg = imgUrl.value.url
}


const submitFrom = async (MethedType: string) => {
     if (MethedType === '添加') {
          let result = await AddUser(form)
          if (result.data.code === 200) {
               RefreshUser();
               ElMessage.success('用户添加成功.....')

          } else {
               ElMessage.error('用户添加失败.....')
          }
     } else {
          let result = await EditUser(form)
          if (result.data.code === 200) {
               RefreshUser();
               ElMessage.success('用户修改成功.....')
          } else {
               ElMessage.error('用户修改失败.....')
          }
     }
     centerDialogVisible.value = false
}


const delUser = (id: number) => {
     ElMessageBox.confirm(
          `您确定删除用户：${id} ?`,
          '提示',
          {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning',
          }
     )
          .then(async () => {
               let result = await DeleteUser(id);
               if (result.data.code === 200) {
                    ElMessage({
                         type: 'success',
                         message: '删除成功！',
                    })
                    // 刷新数据
                    RefreshUser();
               }

          })
          .catch(() => {
               ElMessage({
                    type: 'info',
                    message: '删除取消',
               })
          })


}

</script>

<style scoped>
.top {
     width: 98%;
     height: 30px;
     background-color: white;
     padding: 20px 5px;
     padding-left: 20px;
     border-radius: 5px;
     display: flex;
     /* box-shadow: 水平阴影 垂直阴影 
			  模糊距离 阴影尺寸 阴影颜色 内外阴影；*/
     box-shadow: 2px 2px 20px 2px rgb(197, 197, 197);
}

.btnDiv {
     margin-left: 50px;
}

.content {
     background-color: white;
     margin-top: 20px;
     box-shadow: 2px 2px 20px 2px rgb(197, 197, 197);
}

.tool {
     display: flex;
     /* 交叉轴的中点对齐。 */
     justify-content: space-between;
     align-items: center;
}

.right {
     display: flex;
     align-content: center;
}

.Refresh {
     margin: 0 15px;
}

.List {
     margin-top: 10px;
}
</style>